from django.contrib import admin
from django import forms
from .models import ZbirdAccount, WalmartAccount, Keyword, Product, SkuKeywordsHistory, skus
import uuid
from django.utils.html import format_html
from django.utils import timezone
from django.urls import path
from django.shortcuts import render, redirect
from django.contrib import messages
import pandas as pd
from io import BytesIO
from django.contrib import admin
from django.urls import path
from django.http import HttpResponseRedirect
from django.utils.html import format_html
from django.contrib import messages
from django.urls import reverse
from .models import Product, WalmartAccount, skus
import traceback
class UserAwareModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        if self.user:
            self.fields['username'].initial = self.user.username

class ZbirdAccountForm(UserAwareModelForm):
    class Meta:
        model = ZbirdAccount
        fields = '__all__'

class WalmartAccountForm(UserAwareModelForm):
    class Meta:
        model = WalmartAccount
        fields = '__all__'

class KeywordForm(UserAwareModelForm):
    class Meta:
        model = Keyword
        fields = '__all__'

class ProductForm(UserAwareModelForm):
    class Meta:
        model = Product
        fields = '__all__'

class IsFollowingFilter(admin.SimpleListFilter):
    title = '是否跟卖'
    parameter_name = 'is_following' 

    def lookups(self, request, model_admin):
        return (
            (1, '是'),
            (0, '否'),
        )

    def queryset(self, request, queryset):
        if self.value() == '1':
            return queryset.filter(is_following=1)
        if self.value() == '0':
            return queryset.filter(is_following=0)
        return queryset

@admin.register(ZbirdAccount)
class ZbirdAccountAdmin(admin.ModelAdmin):
    form = ZbirdAccountForm
    list_display = ('tag','epname', 'loginname', 'username', 'create_date', 'update_date')
    search_fields = ('epname', 'username')
    list_filter = ('create_date', 'update_date')
    ordering = ('-create_date',)
    readonly_fields = ('username',)
    class Meta:
        verbose_name = '账号'
        verbose_name_plural = '账号管理'

    def get_changeform_initial_data(self, request):
        return {'username': request.user.username}

    def save_model(self, request, obj, form, change):
        if not change:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)

@admin.register(WalmartAccount)
class WalmartAccountAdmin(admin.ModelAdmin):
    form = WalmartAccountForm
    list_display = ('orderindex', 'username',  'tag', 'loginname', 'zbird_account', 'create_date', 'update_date')
    search_fields = ('username',)
    list_filter = ('create_date', 'update_date')
    ordering = ('-create_date',)
    readonly_fields = ('username',)
    class Meta:
        verbose_name = '沃尔玛账号'
        verbose_name_plural = '沃尔玛账号管理'

    def get_changeform_initial_data(self, request):
        return {'username': request.user.username}

    def save_model(self, request, obj, form, change):
        if not change:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)

@admin.register(Keyword)
class KeywordAdmin(admin.ModelAdmin):
    form = KeywordForm
    list_display = ('username', 'keyword', 'is_prohibited', 'create_date', 'update_date')
    search_fields = ('keyword',)
    list_filter = ('is_prohibited', 'create_date')
    ordering = ('-create_date',)
    readonly_fields = ('username',)
    class Meta:
        verbose_name = '关键词'
        verbose_name_plural = '关键词管理'

    def get_changeform_initial_data(self, request):
        return {'username': request.user.username}

    def save_model(self, request, obj, form, change):
        if not change:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    change_list_template = 'admin/product_change_list.html'
    def get_model_perms(self, request):
        return {
            'add': self.has_add_permission(request),
            'change': self.has_change_permission(request),
            'delete': self.has_delete_permission(request),
            'view': self.has_view_permission(request),
        }
    def get_walmart_accounts(self, request):
        return WalmartAccount.objects.filter(username=request.user.username)
    list_display = ('productid','short_product_name', 'is_following', 'username',  'sku', 'upc','price', 'category', 'display_image','current_cart_seller', 'create_date', 'update_date')
    list_display_links = ('productid', 'short_product_name')
    # list_editable = ('sku',)
    search_fields = ('product_name', 'sku', 'category')
    list_filter = ('category', 'is_following')
    fields = ('productid', 'product_name', 'sku', 'price', 'category', 'create_date', 'update_date')
    readonly_fields = ('create_date', 'update_date')
    actions = ['mark_as_following', 'mark_as_not_following', 'fetch_upc_action']
    class Meta:
        verbose_name = '产品信息'
        verbose_name_plural = '产品信息管理'

    def short_product_name(self, obj):
        """Display the first 25 characters of the product name followed by ellipses if needed."""
        return format_html(
            '<div style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{}</div>',
            obj.product_name
        )
    short_product_name.short_description = '产品名称'

    def display_image(self, obj):
        """Display the product image in the admin list view with hover effect."""
        if obj.image:
            return format_html(
                '<div style="position: relative; display: inline-block;">'
                '<img src="{}" style="max-height: 50px; transition: transform 0.2s; z-index: 1;" class="product-image" />'
                '<style>'
                '.product-image:hover {{ transform: scale(12); z-index: 10000; position: relative; }}'
                '</style>'
                '</div>',
                obj.image
            )
        return "No Image"
    display_image.short_description = "产品图片"



    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs

    def get_changeform_initial_data(self, request):
        return {'username': request.user.username}

    def save_model(self, request, obj, form, change):
        if not change:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)
    def handle_follow_sell(self, request):
        if request.method == 'POST':
            account_id = request.POST.get('walmart_account')
            if not account_id or not account_id.isdigit():
                messages.error(request, '必须选择一个有效的Walmart账号')
                return HttpResponseRedirect(reverse('admin:app_product_changelist'))          
            selected_ids = request.POST.getlist('_selected_action')
            try:
                # 创建跟卖记录+
                for product_id in selected_ids:
                    product=Product.objects.get(id=product_id)
                    skus.objects.create(
                        walmart_account_id=account_id,
                        is_following=1,
                        username=request.user.username,
                        sku=product.sku,
                        price=product.price,
                        category=product.category,
                        product_name=product.product_name,
                        image=product.image,
                        link=product.link,
                        rating=product.rating,
                        reviews=product.reviews,
                        create_date=timezone.now(),
                        update_date=timezone.now(),
                        hasexcept=product.hasexcept
                    )
                    product.delete()
                messages.success(request, f'成功创建{len(selected_ids)}条跟卖记录')
            except Exception as e:
                messages.error(request, f'操作失败: {str(e)}')
                traceback.print_exc()
                
            return HttpResponseRedirect(reverse('admin:app_product_changelist'))
    
    # 添加自定义URL
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('follow-sell/', self.handle_follow_sell, name='follow-sell'),
        ]
        return custom_urls + urls
    
    # 在页面添加自定义控件
    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        extra_context['walmart_accounts'] = self.get_walmart_accounts(request)
        return super().changelist_view(request, extra_context=extra_context)
@admin.register(SkuKeywordsHistory)
class SkuKeywordsHistoryAdmin(admin.ModelAdmin):
    list_display = ('sku', 'keywords', 'opdate',  'fromprice', 'toprice', 'username')
    search_fields = ('sku', 'keywords', 'username')
    list_filter = ('opdate', 'username')
    class Meta:
        verbose_name = 'SKU关键词历史'
        verbose_name_plural = 'SKU关键词历史记录'
    def get_model_perms(self, request):
        return {
            'add': self.has_add_permission(request),
            'change': self.has_change_permission(request),
            'delete': self.has_delete_permission(request),
            'view': self.has_view_permission(request),
        }
    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return True

class ImportForm(forms.Form):
    excel_file = forms.FileField(label='上传 SKU Excel(文件只有1列，SKU) 文件')

@admin.register(skus)
class SkusAdmin(admin.ModelAdmin):
    list_display = ('id', 'is_following', 'sku', 'walmart_account', 'price','username','upc', 'current_cart_seller','display_image','newprice','rating','reviews')
    list_editable = ('upc', 'price')
    list_filter = ('walmart_account', 'username', 'current_cart_seller')
    search_fields = ('sku', 'username', 'upc',  'price', 'current_cart_seller')
    fields = ('sku', 'walmart_account', 'username', 'current_cart_seller', 'own_follow_price', 'upc', 'newprice', 'newsku', 'taxcode', 'rating', 'reviews', 'hasexcept')
    readonly_fields = ('id', 'username')
    actions = ['mark_as_following', 'mark_as_not_following']
    class Meta:
        verbose_name = 'SKU管理'
        verbose_name_plural = 'SKU管理'
    def display_image(self, obj):
        """Display the product image in the admin list view with hover effect."""
        if obj.image:
            return format_html(
                '<div style="position: relative; display: inline-block;">'
                '<img src="{}" style="max-height: 50px; transition: transform 0.2s; z-index: 1;" class="product-image" />'
                '<style>'
                '.product-image:hover {{ transform: scale(12); z-index: 10000; position: relative; }}'
                '</style>'
                '</div>',
                obj.image
            )
        return "No Image"
    display_image.short_description = "产品图片"
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('import/', self.admin_site.admin_view(self.import_skus), name='import_skus'),
        ]
        return custom_urls + urls

    def import_skus(self, request):
        if request.method == 'POST':
            form = ImportForm(request.POST, request.FILES)
            if form.is_valid():
                excel_file = request.FILES['excel_file']
                df = pd.read_excel(BytesIO(excel_file.read()))
                walmart_account_id = request.POST.get('walmart_account')
                walmart_account = WalmartAccount.objects.get(id=walmart_account_id)
                username = request.user.username

                for sku in zip(df.iloc[:, 0]):   
                    skus.objects.update_or_create(
                        sku=str(sku[0]).replace('.0',''),
                        walmart_account=walmart_account,
                        username=username,
                        create_date=timezone.now(),
                        update_date=timezone.now()
                    )
                messages.success(request, 'SKU,PRICE 数据导入成功！')
                return redirect('..')
        else:
            form = ImportForm()
        
        context = self.admin_site.each_context(request)
        context['opts'] = self.model._meta
        context['form'] = form
        context['walmart_accounts'] = WalmartAccount.objects.all()
        return render(request, 'admin/import_skus.html', context)

    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        extra_context['import_url'] = 'import/'
        return super().changelist_view(request, extra_context=extra_context)

    def short_product_name(self, obj):
        """Display the first 25 characters of the product name followed by ellipses if needed."""
        return format_html(
            '<div style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{}</div>',
            obj.product_name
        )
    short_product_name.short_description = 'Product Name'

    def display_image(self, obj):
        """Display the product image in the admin list view with hover effect."""
        if obj.image:
            return format_html(
                '<div style="position: relative; display: inline-block;">'
                '<img src="{}" style="max-height: 50px; transition: transform 0.2s; z-index: 1;" class="product-image" />'
                '<style>'
                '.product-image:hover {{ transform: scale(12); z-index: 10000; position: relative; }}'
                '</style>'
                '</div>',
                obj.image
            )
        return "No Image"
    display_image.short_description = "产品图片"
 

    def save_model(self, request, obj, form, change):
        if not obj.username:
            obj.username = request.user.username
        super().save_model(request, obj, form, change)